package topofstack.networkserverutils;

import topofstack.networkserverutils.bean.PingInfo;
import topofstack.networkserverutils.bean.SiteInfo;
import topofstack.networkserverutils.bean.TraceRouteInfo;
import topofstack.networkserverutils.mail.SendMailSSL;
import topofstack.networkserverutils.net.Nslookup;
import topofstack.networkserverutils.net.Ping;
import topofstack.networkserverutils.net.TraceRoute;
import topofstack.networkserverutils.util.Constants;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MailServerDetails extends Activity {
	
	public static final String SERVER_NAME = "name";
	
	private String serverName;
	
	private TextView aRecord;
	private TextView ping;
	private TextView traceRoute;
	private Button smtp;
	
	private ProgressDialog dialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.server_details);
		
		serverName = getIntent().getExtras().getString(SERVER_NAME);
		
		aRecord = (TextView) findViewById(R.id.server_A_record);
		ping = (TextView) findViewById(R.id.server_ping);
		traceRoute = (TextView) findViewById(R.id.server_traceroute);
		smtp = (Button) findViewById(R.id.server_smtp);
		smtp.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View arg0) {
				Intent intent = new Intent(getBaseContext(), SmtpTest.class);
				intent.putExtra(SmtpTest.HOST_NAME, serverName);
				startActivity(intent);
			}
		});
		
		new RetriveData().execute(new Void[0]);
		
		dialog = new ProgressDialog(this);
		dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		dialog.setMessage(Constants.DIALOG_MESSAGE);
		dialog.setIndeterminate(true);
		dialog.show();
	}
	
	private class RetriveData extends AsyncTask<Void, Void, Void> {
		
		private SiteInfo siteInfo;
		private PingInfo pingInfo;
		private TraceRouteInfo traceRouteInfo;
		
		@Override
		protected Void doInBackground(Void... params) {
			
			siteInfo = Nslookup.getA(serverName);
			
			if(siteInfo != null) {
				pingInfo = Ping.get(siteInfo.ipAddress);
				traceRouteInfo = TraceRoute.get(siteInfo.ipAddress);
			}
			
			return null;
		}
		
		@Override
		protected void onPostExecute(Void v) {
			
			if(siteInfo == null || pingInfo == null || traceRouteInfo == null)
				Toast.makeText(getBaseContext(), Constants.ERROR_MESSAGE, 
						Toast.LENGTH_SHORT).show();
			else {
				aRecord.setText(siteInfo.toString());
				ping.setText(pingInfo.toString());
				traceRoute.setText(traceRouteInfo.toString());
			}
			
			dialog.cancel();
		}
	}
}
